package com.eportal.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.eportal.base.BaseDAO;
import com.eportal.controller.background.TOpenLogController;
import com.eportal.dao.*;
import com.eportal.domain.*;
import com.eportal.entity.*;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.exception.NotUniqueException;
import com.eportal.service.BaseServiceImpl;
import com.eportal.service.FuncMainService;
import com.eportal.service.TAgentService;
import com.eportal.vo.controller.background.funcmain.ApplyDetailVO;
import com.eportal.vo.controller.background.funcmain.FeeAlipayAuthSelectVO;
import com.eportal.vo.controller.background.funcmain.FuncMain4AgentListVO;
import com.eportal.vo.controller.background.funcmain.ViewDetailVO;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service("funcMainService")
public class FuncMainServiceImpl extends BaseServiceImpl<FuncMainEntity> implements FuncMainService{

	private static Logger logger = LoggerFactory.getLogger(FuncMainServiceImpl.class.getName());

	@Resource(name="dao")
	private BaseDAO dao;

	@Autowired
	TAgentService agentService;

	@Resource
	private FuncMainEntityMapper funcMainDao;

	@Resource
	private TCommunityEntityMapper tCommunityDao;

	@Resource
	private FeeAlipayAuthEntityMapper feeAlipayAuthDao;

	@Resource
	private FuncAgentEntityMapper funcAgentDao;

	@Resource
	private FuncApplyEntityMapper funcApplyDao;

	@Override
	public List<FuncMain> list(JqGridPager jqGridPager) {

		String hql="from FuncMain ";
		List<FuncMain> list =  dao.query(hql);
		return list;
	}


	@Override
	public List<Map<String, Object>> list4agent(JqGridPager jqGridPager,String agtcode) {
		String hql="from FuncMain ";
		List<FuncMain> list =  dao.query(hql);
		int i = dao.countQuery("select count(*) from TCommunity where agtcode='"+agtcode+"'");
		 List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
		for(FuncMain bean:list){
			Map map = new HashMap();
        	map.put("CNAME", bean.getCname());
        	map.put("SID", bean.getSid());
        	map.put("COMMUNITY_COUNT", i);
        	int open = dao.countQuery("select count(*)  from FuncDetail where main_id='"+bean.getSid()+"' and agtcode='"+agtcode+"' and status='1'");
        	map.put("COMMUNITY_OPEN_COUNT", open);
        	map.put("APPLY_TIME", new Date());
        	map.put("AUDIT_TIME", new Date());
        	datalist.add(map);
		}
		return datalist;
	}


	@Override
	public FuncMain get(Long sid) {
		return (FuncMain)dao.getById(FuncMain.class, sid);
	}


	@Override
	public void apply(String[] communityArr, String[] alipayArr, String mainId, String agtCode,Long sysoptid) throws Exception {
		if(communityArr.length==alipayArr.length){
			for(int i=0;i<communityArr.length;i++){
				String cid = communityArr[i];
				if(cid!=null&&cid.length()>0){
					String aid = alipayArr[i];

					TCommunity community = (TCommunity)dao.getById(TCommunity.class, Long.valueOf(cid));
					FeeAlipayAuth alipayAuth = (FeeAlipayAuth)dao.getById(FeeAlipayAuth.class,  Long.valueOf(aid));
					if(!community.getAgtCode().equals(agtCode)){
						throw new MdKnownRunTimeException("小区信息不正确");
					}
					if(!alipayAuth.getAgtcode().equals(agtCode)){
						throw new MdKnownRunTimeException("支付宝账号信息不正确");
					}
					FuncApply apply = new FuncApply();
					apply.setAgtcode(agtCode);
					apply.setAlipayId(String.valueOf(alipayAuth.getSid()));
					apply.setCusername(String.valueOf(sysoptid));
					apply.setCommunityid(cid);
					apply.setStatus("1");
					apply.setCtime(new Date());
					apply.setMainId(mainId);
					dao.save(apply);
					updateFuncAgent(mainId,agtCode);

				}

			}
		}

	}


	//更新最近的申请时间
	private void updateFuncAgent(String mainId, String agtCode) throws Exception {
		List<FuncAgent> list = dao.query("from FuncAgent where mainId='"+mainId+"' and agtcode='"+agtCode+"'");
		if(list.size()>0){
			FuncAgent bean = list.get(0);
			bean.setLastApplyTime(new Date());;
			dao.update(bean);
		}else{
			FuncAgent bean = new FuncAgent();
			bean.setAgtcode(agtCode);
			bean.setMainId(mainId);
			bean.setCtime(new Date());
			bean.setLastApplyTime(new Date());
			dao.save(bean);
		}

	}


	@Override
	public List<Map<String, Object>> listDetailByAdmin(String funcAgentId) throws NotUniqueException {
		FuncAgent funcAgent = (FuncAgent)dao.getById(FuncAgent.class, Long.valueOf(funcAgentId));
		return getDetailList( funcAgent.getMainId(),funcAgent.getAgtcode());
	}


	/**
	 *
	 * @param funcMainId
	 * @param agtCode
	 * @return
	 * @throws NotUniqueException
	 * @see FuncMainServiceImpl#listDetail(Long, String, Sysopt, int)  mybatis版
	 */
	@Override
	public List<Map<String, Object>> listDetail(String funcMainId, String agtCode) throws NotUniqueException {

		return getDetailList(funcMainId, agtCode);
	}

	private List getDetailList(String funcMainId,String agtCode) throws NotUniqueException{
		TAgent agent = agentService.get(agtCode);
		FuncMain main = (FuncMain)dao.getById(FuncMain.class,Long.valueOf(funcMainId));
		List<TCommunity> list = dao.query("from TCommunity where agtcode='"+agent.getAgtCode()+"' and status='1' ");


		List datalist = new ArrayList();
		for(TCommunity bean:list){
			Map map = new HashMap();
			map.put("agtname", agent.getAgtName());
			map.put("mainName",main.getCname());
			map.put("communityname",bean.getCommunityName());
			map.put("communityid",bean.getSid());
			map.put("mainId",main.getSid());
			String hql="from FuncDetail where mainId='"+main.getSid()+"' and communityid='"+bean.getSid()+"'";
			FuncDetail  fd = (FuncDetail)dao.getUniqueFirst(hql);
			if(fd!=null){
				if("1".equals(fd.getStatus())){
					map.put("status","3");	//正常开通
				}else if("2".equals(fd.getStatus())){
					map.put("status","4");//已关闭
				}
				FeeAlipayAuth ali = (FeeAlipayAuth)dao.getById(FeeAlipayAuth.class,Long.valueOf(fd.getAlipayId()));
				map.put("login_account",ali.getLoginAccount());
			}else{
				FuncApply apply = (FuncApply)dao.getFirst("from FuncApply where mainId='"+main.getSid()+"' and communityid='"+bean.getSid()+"' order by sid desc");
				if(apply!=null){
					if("1".equals(apply.getStatus())){
						map.put("status","1");//待审
					}else if("3".equals(apply.getStatus())){
						map.put("status","2");//审核不通过
					}
				}else{
					map.put("status","5");//未申请
				}

			}


			datalist.add(map);
		}
		return datalist;
	}


//todo-----------------------------------------------------------------------------------------------


	/**
	 * 缴费开通申请列表
	 *
	 * @param pageEntity 分页对象
	 * @param agtCode 	 合作方code
	 * @param user       当前用户
	 * @param userRole   当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/24 上午11:43
	 * @see FuncMainServiceImpl#list4agent(JqGridPager, String)
	 */
	@Override
	public PageInfo<FuncMain4AgentListVO> queryForAgentPage(PageEntity pageEntity,String agtCode, Sysopt user, int userRole) {
		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}
		List<FuncMain4AgentListVO> list = funcMainDao.queryForAgentList(agtCode, user, userRole);
		return new PageInfo<>(list);
	}

	/**
	 * 缴费开通申请详情
	 *
	 * @param funcMainId    FUNC_MAIN表sId
	 * @param agtCode  		合作方我猜的
	 * @param user     		当前用户
	 * @param userRole 		当前用户userRole
	 * @return
	 * @see FuncMainServiceImpl#listDetail(String, String)
	 */
	@Override
	public List<ViewDetailVO> listDetail(Long funcMainId,String agtCode, Sysopt user, int userRole) {
		return funcMainDao.getListDetail(funcMainId,agtCode,user,userRole);
	}

	/**
	 * 缴费开通申请详情2（申请时使用）
	 * @param sId      FUNC_MAIN表sId
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/24 下午4:18
	 * @see com.eportal.action.background.FuncMainAction#applyView()
	 */
	@Override
	public JSONObject applyDetail(Long sId, Sysopt user, int userRole) {
		JSONObject json = new JSONObject();
		try {
			//获取支付宝账号
			List<FeeAlipayAuthSelectVO> loginAccountList = feeAlipayAuthDao.getLoginAccountListByAgtCode(user.getAgtCode());

			List<ApplyDetailVO> list = funcMainDao.getApplyDetail(sId, user, userRole);

			for (ApplyDetailVO applyDetailVO : list) {
				applyDetailVO.setsId(sId);
				applyDetailVO.setLoginAccountList(loginAccountList);
			}
			json.put("code",1);
			json.put("msg","ok");
			json.put("data",list);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取缴费申请详情2异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 缴费开通申请
	 *
	 * @param sId          sId
	 * @param communityIds 小区id集合 用,分割
	 * @param alipayIds    支付宝账号id集合 用,分割  （FEE_ALIPAY_AUTH表sId）
	 * @param agtCode      合作方code
	 * @param sysoptId     当前用户id
	 * @return
	 * @author Saber
	 * @Date 2017/8/25 上午9:35
	 * @see FuncMainServiceImpl#apply(String[], String[], String, String, Long)
	 */
	@Transactional
	@Override
	public JSONObject apply(Long sId, String communityIds, String alipayIds, String agtCode,Long sysoptId) {
		JSONObject json = new JSONObject();
		try {
			String[] communityArr = communityIds.split(",");
			String[] alipayArr = alipayIds.split(",");
			if(communityArr.length==alipayArr.length){
				for(int i=0;i<communityArr.length;i++){
					String cid = communityArr[i];
					if(cid!=null&&cid.length()>0){
						String aid = alipayArr[i];

						TCommunityEntity community = tCommunityDao.selectByPrimaryKey(Long.valueOf(cid));
						FeeAlipayAuthEntity alipayAuth = feeAlipayAuthDao.selectByPrimaryKey(Long.valueOf(aid));
						if(!community.getAgtcode().equals(agtCode)){
							throw new MdKnownRunTimeException("小区信息不正确");
						}
						if(!alipayAuth.getAgtcode().equals(agtCode)){
							throw new MdKnownRunTimeException("支付宝账号信息不正确");
						}
						FuncApplyEntity apply = new FuncApplyEntity();
						apply.setAgtcode(agtCode);
						apply.setAlipayId(String.valueOf(alipayAuth.getSid()));
						apply.setCusername(String.valueOf(sysoptId));
						apply.setCommunityid(cid);
						apply.setStatus("1");
						apply.setCtime(new Date());
						apply.setMainId(String.valueOf(sId));
						funcApplyDao.insertSelective(apply);
						updateFuncAgent(sId, agtCode);

					}

				}
				json.put("code",1);
				json.put("msg","操作成功");
				json.put("data",sId);
				return json;
			}
			json.put("code",0);
			json.put("msg","参数错误");
			json.put("data",null);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("缴费开通申请异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 更新最近的申请时间
	 * @author Saber
	 * @Date 2017/8/25 上午9:58
	 * @param mainId
	 * @param agtCode
	 * @see FuncMainServiceImpl#updateFuncAgent(String, String)
	 * @throws Exception
	 */
	private void updateFuncAgent(Long mainId, String agtCode) throws Exception {
		List<FuncAgentEntity> list = funcAgentDao.getListByMainIdAndAgtCode(mainId,agtCode);
		if(list.size()>0){
			FuncAgentEntity bean = list.get(0);
			bean.setLastApplyTime(new Date());
			funcAgentDao.updateByPrimaryKeySelective(bean);
		}else{
			FuncAgentEntity bean = new FuncAgentEntity();
			bean.setAgtcode(agtCode);
			bean.setMainId(String.valueOf(mainId));
			bean.setCtime(new Date());
			bean.setLastApplyTime(new Date());
			funcAgentDao.insertSelective(bean);
		}

	}
}
